import type {
  CreateCrudOptionsProps,
  CreateCrudOptionsRet,
} from '@fast-crud/fast-crud';

import type { Ref } from 'vue';

import type { FormRulesExt } from '#/api';

import { RuleType, UserApi } from '#/api';
import { $t } from '#/locales';

export function createCrudOptions(
  _props: CreateCrudOptionsProps,
): CreateCrudOptionsRet {
  return {
    crudOptions: {
      request: { addRequest: UserApi.updatePasswordRequest },
      form: { mode: 'add', col: { span: 24 } },
      columns: {
        id: {
          title: 'ID',
          type: 'text',
          form: { show: false },
        },
        oldPassword: {
          title: '当前密码',
          type: 'password',
          form: {
            component: {
              autocomplete: 'new-password',
              'show-password-on': 'click',
            },
          },
        },
        password: {
          title: $t('devOperation.tenant.defUser.password'),
          type: 'password',
          form: {
            component: {
              autocomplete: 'new-password',
              'show-password-on': 'click',
            },
          },
        },
        confirmPassword: {
          title: '确认密码',
          type: 'password',
          form: {
            component: {
              autocomplete: 'off',
              'show-password-on': 'click',
            },
          },
        },
      },
    },
  };
}

export const frontRules = (formRef: Ref): FormRulesExt => {
  return {
    confirmPassword: {
      type: RuleType.and,
      rules: [
        {
          trigger: ['blur', 'change'],
          type: 'string',
          asyncValidator: async (_: any, value: string, callback) => {
            if (value) {
              const { getFormData } = formRef.value;
              const model = await getFormData();
              if (value !== model.password) {
                return callback('2次密码不一致');
              }
              return callback();
            }
          },
        },
      ],
    },
  };
};
